<template>
    <div class="app-container">
        <!-- 搜索 -->
        <el-row type="flex" justify="end" style="margin-bottom: 20px">
            <!-- 根据账号搜索 -->
            <el-col :span="3" style="margin-right: 10px;">
                <el-input
                    v-model.trim="params.username"
                    placeholder="请输入账号"
                    clearable
                    @clear="getUser"
                ></el-input>
            </el-col>
            <el-col :span="3" style="margin-right: 10px;">
                <el-select v-model="params.userType" placeholder="请选择">
                    <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    ></el-option>
                </el-select>
            </el-col>
            <!-- 搜索重置按钮 -->
            <el-button type="primary" @click="getUser" icon="el-icon-search"></el-button>
            <el-button type="primary" @click="reset">重置</el-button>
            <!-- <el-button type="primary" @click="addDialog = true;">添加</el-button> -->
        </el-row>
        <!-- 表格展示 -->
        <el-table :data="tableData" v-loading="loading" stripe border>
            <el-table-column type="selection"></el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="username" label="用户名"></el-table-column>
            <el-table-column prop="roleName" label="身份"></el-table-column>
            <el-table-column label="头像" align="center">
                <template scope="scope">
                    <img :src="scope.row.avatar" alt style="width:40px;height: 40px;" />
                </template>
            </el-table-column>
            <!-- 操作按钮 -->
            <el-table-column label="操作" width="300">
                <template slot-scope="scope">
                    <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button
                        size="mini"
                        type="danger"
                        @click="handleDelete(scope.$index, scope.row)"
                    >删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 修改密码弹出框 -->
        <el-dialog title="编辑" :visible.sync="UpdatePwdDialog">
            <el-form :model="UpdatePwdForm" :rules="rules"
                    ref="UpdatePwdForm">
                <el-form-item label="个人头像">
                    <el-upload
                        class="avatar-uploader"
                        action="/api/vue-admin-template/user/updatePortrait"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload"
                        name="avatar"
                    >
                        <!-- :http-request="uploadImage" -->
                        <img v-if="UpdatePwdForm.avatar" :src="UpdatePwdForm.avatar" class="avatar" />
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <div style="color: gray">上传图片只能是 JPG/PNG 格式,图片大小不能超过 3MB!</div>
                <!-- 修改密码 -->
                <el-form-item
                    label="新密码"
                    :label-width="formLabelWidth"
                     prop="password"
                >
                    <el-input v-model="UpdatePwdForm.password" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-col style="display: flex; justify-content: center;">
                        <el-form-item>
                            <el-button type="primary" @click="submitUpdatePwdForm()">提交</el-button>
                            <el-button @click="resetForm()">重置</el-button>
                        </el-form-item>
                    </el-col>
                </el-form-item>
            </el-form>
        </el-dialog>

        <!-- 分页 -->
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="params.pageCurrent"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="params.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
        ></el-pagination>
    </div>
</template>
<script>
import { getUser, update } from '@/api/user'
export default {
    data() {
        return {
            tableData: [],
            formLabelWidth: "70px",
            loading: false,
            UpdatePwdDialog: false,
            total: null,
            options: [
                {
                    value: 'admin',
                    label: '超级管理员'
                },
                {
                    value: 'housemaster',
                    label: '宿管'
                },
                {
                    value: 'student',
                    label: '学生'
                }
            ],
            params: {
                pageCurrent: 1,
                pageSize: 10,
                userType: null,
                username: ""
            },
            UpdatePwdForm: {
                id: "",
                username: "",
                password: "",
                avatar: "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif"
            },
            rules: {
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 8, message: '长度在 6 到 8 个字符', trigger: 'blur' },
                ]
            }
        }
    },
    created() {
        this.getUser()
    },
    methods: {
        // 分页
        // 监听页码变化
        handleCurrentChange(newPage) {
            this.params.pageCurrent = newPage
            this.getUser()
        },
        // 监听size变化
        handleSizeChange(newSize) {
            this.params.pageSize = newSize
            this.getUser()
        },
        // 获取用户信息
        async getUser() {
            await getUser(this.params).then((res) => {
                console.log(res);
                this.loading = true
                setTimeout(() => {
                    this.tableData = res.data.records
                    // 把total转为number类型
                    this.total = Number(res.data.total)
                    this.loading = false
                }, 200);

            })
        },
        // 编辑用户
        handleEdit(index, row) {
            console.log(row);
            this.UpdatePwdDialog = true
            this.UpdatePwdForm.username = JSON.parse(JSON.stringify(row.username))
            this.UpdatePwdForm.avatar = JSON.parse(JSON.stringify(row.avatar))
            this.UpdatePwdForm.id = JSON.parse(JSON.stringify(row.id))
        },
        submitUpdatePwdForm() {
            this.$refs.UpdatePwdForm.validate((valid) => {
                if (valid) {
                    update(this.UpdatePwdForm).then((res) => {
                        if (res.code === "200") {
                            this.getUser()
                            this.$message.success('更新成功')
                            this.UpdatePwdDialog = false
                        } else {
                            this.$message.error('更新失败')
                        }
                    })
                }
            })

        },


        handleAvatarSuccess() {
            this.UpdatePwdForm.avatar = 'https://' + response.data;
            console.log(this.UpdatePwdForm.avatar);
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === "image/jpeg";
            const isPNG = file.type === "image/png";
            const isGIF = file.type === "image/gif";
            const isLt2M = file.size / 1024 / 1024 < 1;
            const flag = !isJPG && !isGIF && !isPNG;
            if (flag) {
                this.$message.error("上传头像图片只能是 JPG/PNG/GIF 格式!");
            }
            if (!isLt2M) {
                this.$message.error("上传头像大小不能超过 1MB!");
            }
            return !flag && isLt2M;
        },


        // 搜索重置按钮
        async reset() {
            this.params.userType = null;
            this.params.username = "";
            await getUser(this.params).then((res) => {
                this.loading = true;
                setTimeout(() => {
                    this.tableData = res.data.records;
                    this.loading = false;
                }, 200);
            });
        },
    },
}
</script>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>